package net.guerlab.smart.wx.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.smart.wx.api.WxAppApi;
import net.guerlab.smart.wx.api.feign.FeignWxAppApi;
import net.guerlab.smart.wx.core.domain.WxAppDTO;
import net.guerlab.smart.wx.core.exception.WxAppInvalidException;
import net.guerlab.smart.wx.core.searchparams.WxAppSearchParams;
import net.guerlab.spring.searchparams.SearchParamsUtils;
import net.guerlab.web.result.ListObject;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.*;

/**
 * @author guer
 */
@Configuration
@AutoConfigureAfter(WxAppApiLocalServiceAutoConfigure.class)
public class WxAppApiFeignAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean(WxAppApi.class)
    public WxAppApi wxAppApiFeignWrapper(FeignWxAppApi api) {
        return new WxAppApiFeignWrapper(api);
    }

    @AllArgsConstructor
    private static class WxAppApiFeignWrapper implements WxAppApi {

        private FeignWxAppApi api;

        @Override
        public WxAppDTO findOne(String appId) {
            return Optional.ofNullable(api.findOne(appId).getData()).orElseThrow(WxAppInvalidException::new);
        }

        @Override
        public ListObject<WxAppDTO> findList(WxAppSearchParams searchParams) {
            Map<String, Object> params = new HashMap<>(8);
            SearchParamsUtils.handler(searchParams, params);
            return Optional.ofNullable(api.findList(params).getData()).orElse(ListObject.empty());
        }

        @Override
        public List<WxAppDTO> findAll(WxAppSearchParams searchParams) {
            Map<String, Object> params = new HashMap<>(8);
            SearchParamsUtils.handler(searchParams, params);
            return Optional.ofNullable(api.findAll(params).getData()).orElse(Collections.emptyList());
        }
    }

}
